package top.kaoshanji.p1ch04a;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;

/**
 * 代码清单 p1ch04a-06：URL编码方式
 * author kaoshanji
 * ^_^
 * create time 2025/1/14 19:39
 */
public class URLEncoderExample01 {

    private static final Logger logger = LogManager.getLogger(URLEncoderExample01.class);

    public static void main(String[] args) throws IOException {
        logger.info("...代码清单 p1ch04a-06：URL编码方式...");

        URLEncoderExample01 example = new URLEncoderExample01();
        example.search("你好");

    }

    public void search(String keyword) throws IOException {
        String url = "http://www.baidu.com/s?wd=" + URLEncoder.encode(keyword, "GB18030");
        InputStream input = new URL(url).openStream();

        String content = streamToString(input);
        System.out.println(content);
    }

    private String streamToString(InputStream input) throws IOException {
        StringBuilder builder = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(input, "GB18030"));
        char[] buffer = new char[32 * 1024];
        int len = -1;
        while ((len = reader.read(buffer)) != -1) {
            builder.append(buffer, 0, len);
        }
        return builder.toString();
    }

}
